package interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

import model.MemberVO;
import service.v2.ConfigService;
import service.v2.MemberService;
import util.DateParseUtil;
import util.PackageUtil;
import util.PropertieUtil;

public class MemberInterceptor implements HandlerInterceptor {

	@Autowired
	private MemberService memberService;
	@Autowired
	private ConfigService configService;
	
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception ex)
			throws Exception {

	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView mv)
			throws Exception {

	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		String os = request.getHeader("OS");
		if (os != null) {
			os = os.toLowerCase();
		}
		if ("wechat".equals(os) || "web".equals(os)) {
			String member_id = request.getHeader("SECRET");
			String token = request.getHeader("AUTHORIZATION");

			if (token == null || member_id == null) {
				response.setContentType("text/json;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(JSON.toJSONString(PackageUtil.packageParams(403, "forbidden", "", "")));
				out.flush();
				out.close();
				return false;
			}
			MemberVO memberVO = memberService.getMemberByIdCheck(member_id, token, os);
			if (memberVO == null) {
				response.setContentType("text/json;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(JSON.toJSONString(PackageUtil.packageParams(403, "forbidden", "", "")));
				out.flush();
				out.close();
				return false;
			}
			
			memberVO = memberService.checkLoginTime(member_id, PropertieUtil.loadPropertie("token_days"), os);
			if (memberVO == null && "web".equals(os)) {
				response.setContentType("text/json;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(JSON.toJSONString(PackageUtil.packageParams(10712, "登录过期,请重新登录", "", "")));
				out.flush();
				out.close();
				return false;
			} else {
				memberService.updateLastLoginTime(member_id, os);
				return true;
			}

		} else if ("admin".equals(os)) {
			
			String token = configService.loadConfig("INTERFACE_TOKEN");
			String t = request.getHeader("token");
			if (token.equals(t)) {
				return true;
			} else {
				response.setContentType("text/json;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(JSON.toJSONString(PackageUtil.packageParams(403, "forbidden", "", "")));
				out.flush();
				out.close();
				return false;
			}
		}else if("ios".equals(os) || "android".equals(os)){
			//网页
			String page = request.getHeader("PAGE");
			String member_id = request.getHeader("SECRET");
			String token = request.getHeader("AUTHORIZATION");
			if (page != null) {
				if (token == null || member_id == null) {
					if ("ios".equals(os)) {
						response.setContentType("text/html;charset=utf-8");
						PrintWriter out = response.getWriter();
						out.print(
								"<script  language='javascript'> window.webkit.messageHandlers.ios_show_toast.postMessage('您在别的地方已登录');window.webkit.messageHandlers.ios_login_error.postMessage('');</script>");
						out.flush();
						out.close();
						return false;
					} else if ("android".equals(os)) {
						response.setContentType("text/html;charset=utf-8");
						PrintWriter out = response.getWriter();
						out.print("<script  language='javascript'>android.loginOut();</script>");
						out.flush();
						out.close();
						return false;
					}
				}
				MemberVO memberVO = memberService.getMemberByIdCheck(member_id, token, os);
				if (memberVO == null) {
					if ("ios".equals(os)) {
						response.setContentType("text/html;charset=utf-8");
						PrintWriter out = response.getWriter();
						out.print(
								"<script  language='javascript'> window.webkit.messageHandlers.ios_show_toast.postMessage('您在别的地方已登录');window.webkit.messageHandlers.ios_login_error.postMessage('');</script>");
						out.flush();
						out.close();
						return false;
					} else if ("android".equals(os)) {
						response.setContentType("text/html;charset=utf-8");
						PrintWriter out = response.getWriter();
						out.print("<script  language='javascript'>android.loginOut();</script>");
						out.flush();
						out.close();
						return false;
					}
				}

				memberVO = memberService.checkLoginTime(member_id, PropertieUtil.loadPropertie("token_days"), os);
				if (memberVO == null) {
					if ("ios".equals(os)) {
						response.setContentType("text/html;charset=utf-8");
						PrintWriter out = response.getWriter();
						out.print(
								"<script  language='javascript'> window.webkit.messageHandlers.ios_show_toast.postMessage('您在别的地方已登录');window.webkit.messageHandlers.ios_login_error.postMessage('');</script>");
						out.flush();
						out.close();
						return false;
					} else if ("android".equals(os)) {
						response.setContentType("text/html;charset=utf-8");
						PrintWriter out = response.getWriter();
						out.print("<script  language='javascript'>android.loginOut();</script>");
						out.flush();
						out.close();
						return false;
					}
				} else {
					memberService.updateLastLoginTime(member_id, os);
					return true;
				}

			} else {
				if (token == null || member_id == null) {
					response.setContentType("text/json;charset=utf-8");
					PrintWriter out = response.getWriter();
					out.print(JSON.toJSONString(PackageUtil.packageParams(403, "forbidden", "", "")));
					out.flush();
					out.close();
					return false;
				}
				MemberVO memberVO = memberService.getMemberByIdCheck(member_id, token, os);
				if (memberVO == null) {
					response.setContentType("text/json;charset=utf-8");
					PrintWriter out = response.getWriter();
					out.print(JSON.toJSONString(PackageUtil.packageParams(403, "forbidden", "", "")));
					out.flush();
					out.close();
					return false;
				}

				memberVO = memberService.checkLoginTime(member_id, PropertieUtil.loadPropertie("token_days"), os);
				if (memberVO == null) {
					response.setContentType("text/json;charset=utf-8");
					PrintWriter out = response.getWriter();
					out.print(JSON.toJSONString(PackageUtil.packageParams(10712, "登录过期,请重新登录", "", "")));
					out.flush();
					out.close();
					return false;
				} else {
					memberService.updateLastLoginTime(member_id, os);
					return true;
				}
			}
		}

		response.setContentType("text/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.print(JSON.toJSONString(PackageUtil.packageParams(403, "forbidden", "", "")));
		out.flush();
		out.close();
		return false;
        //return true;
		// String url = request.getRequestURI();
		// ManagerVO managerVO = (ManagerVO)
		// request.getSession().getAttribute("admin");
		// if(managerVO != null){
		// return true;
		// }
		// if(url != null && url.endsWith("managerLogin.do")){
		// return true;
		// }
	}

}
